package test.reflection.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReflectionUtils {

	public static Field findField(Class<?> c, String name){
		Field matchingField = null;
		do{
			Field[] fields = c.getDeclaredFields();
			for(Field field : fields){
				if(field.getName().equals(name)){
					matchingField = field;
					break;
				}
			}
			c = c.getSuperclass();
		} while(matchingField==null && c != null);
	
		return matchingField;
	}
	
	public static Method findMethod(Class<?> c, String name){
		Method matchingMethod = null;
		do{
			Method[] methods = c.getDeclaredMethods();
			for(Method method : methods){
				if(method.getName().equals(name)){
					matchingMethod = method;
					break;
				}
			}
			c = c.getSuperclass();
		} while(matchingMethod==null && c != null);
	
		return matchingMethod;
	}
	
	public static Object getFieldValue(Object o, String name) throws IllegalArgumentException, IllegalAccessException{
		Field field = findField(o.getClass(), name);
		if(field != null){
			field.setAccessible(true);
			return field.get(o);
		}
		return null;
	}
}
